const { app, BrowserWindow, ipcMain } = require("electron");
const path = require("path");
const fs = require("fs");

// app.on("ready", () => {
//   const mainWindow = new BrowserWindow({
//     width: 800,
//     height: 600,
//     autoHideMenuBar: true, // Hide the menu bar
//     webPreferences: { // 高级设置
//       nodeIntegration: true,
//     },
//     // x: 0,
//     // y: 0, // Set the window position to the top-left corner
//     // alwaysOnTop: true, // Keep the window always on top
//   });

//     // mainWindow.loadURL("https://cn.bing.com/"); // Load the Bing homepage
//     mainWindow.loadFile("./pages/index.html"); // Load the index.html file
// })

function writeFile(_, data) {
    // console.log(event, data);
    console.log("writeFile::", data);
    fs.writeFileSync("E:\\Desktop\\front-learn\\hello.txt", data);
}

function readFile() {
    const res = fs.readFileSync("E:\\Desktop\\front-learn\\hello.txt").toString();
    console.log("#####", res);
    return res;
}

function createWindow() {
    const mainWindow = new BrowserWindow({
        width: 800,
        height: 600,
        autoHideMenuBar: true,
        webPreferences: {
            preload: path.resolve(__dirname, "./preload.js"),
        }
    });
    ipcMain.on("save-file", writeFile); // 渲染进程向主进程通信 单向：send、on
    ipcMain.handle("read-file", readFile); // 双向通信(双向的渲染和主进程间的通信: invoke、handle
    mainWindow.loadFile("./pages/index.html");
}

console.log("current directory:", __dirname);
console.log("node version: ", process.version);
console.log("node version: ", process.versions.node);
console.log("chrome version: ", process.versions.chrome);
console.log("electron version: ", process.versions.electron);

app.on("ready", () => {
    console.log("App is ready");
    createWindow();
    // Mac
    app.on("activate", () => {
        if (BrowserWindow.getAllWindows().length === 0) {
            createWindow();
        }
    })
})

// 和上面的代码效果相同 app.on
// app.whenReady().then(() => {
//     console.log("App is ready");
//     createWindow();
// })

app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
  }
})

// MacOS specific
// app.on("activate", () => {
//   if (BrowserWindow.getAllWindows().length === 0) {
//     createWindow();
//   }
// })

console.log("Main process started:", "Hello World");